import qs from 'qs'
import { XMLParser } from 'fast-xml-parser'
const fastXMLParser =  XMLParser
let parser = new fastXMLParser()

interface Author{
    name:string
}
interface Paper{
    author:Author[]
    id:string,
    category:string,
    updated:string,
    published:string,
    summary:string,
    title:string,
    link:string[]
}

function paperToString(paper:Paper,summaryLimit:number|null=100):string{
    let summary = paper.summary
    if(summaryLimit){
        let summarySplit = summary.split(" ")
        let newSummaryList = []
        for(let i=0;i<summarySplit.length;i++){
            newSummaryList.push(summarySplit[i])
        }
        summary = newSummaryList.join(" ")
    }
    let authorString = ""
    if(paper.author && paper.author.length>0){
        authorString = paper.author.map((item)=>item.name).join(', ')
    }
    return `{title: "${paper.title}" ,
    url: "${paper.id}" ,
    published: "${paper.published}" ,
    author: "${authorString}" ,
    description: "${summary}"}`
}
async function fetchArxivQuery(query:string){
    let response = fetch(
        `https://export.arxiv.org/api/query?
        ${qs.stringify({
            start:0,
            max_results:3,
            search_query:query
        })}`,
        {
            method: 'GET',
            headers: {
            'Content-Type': 'text/plain',
            },
        }
    )
    let serachResult = (await (await response).text()).toString()
    let serachObject= parser.parse(serachResult)
    let entry:Paper[] = serachObject.feed.entry
    let textArray = []
    for(let i=0;i<entry.length;i++){
        textArray.push(paperToString(entry[i]))
    }
    serachResult = textArray.join("\n")
    return serachResult
}

export {fetchArxivQuery}